<template>
  <basic-container>
     <avue-skeleton v-if="!processFlowDialog"  avatar :rows="4" :number="3"></avue-skeleton>
     <!-- 
      流程处理对话框
     -->
      <avue-form v-if="processFlowDialog" ref="flowProcessForm" v-model="form" :option="option" @submit="onProcessSubmit">
        <template slot-scope="scope" slot="flowExtInfo">
          <div style="">
            <flow-common-area
                :flowExtInfo="flowExtInfo"
                :processData="processData"
                :viewOnly="viewOnly"
                @handleFlowChange="handleFlowExtInfoChange">
            </flow-common-area>
          </div>
        </template>
        <template slot-scope="scope" slot="menuForm">
          <el-row>
            <el-col :span="13"  style="text-align:right">
              <el-button v-if="!viewOnly && processStatus == ''" type="default" icon="el-icon-close" @click="doProcessReject">驳回</el-button>
              <el-button v-if="!viewOnly && processStatus == ''" type="primary" icon="el-icon-check" @click="doProcessSubmit">提交</el-button>
              <el-button v-if="!viewOnly && processStatus != '' && processStatus != '人工撤回'" type="primary" icon="el-icon-refresh-right" @click="onProcessCallBackSubmit">撤回</el-button>
            </el-col>
            <el-col :span="11" style="text-align:right;">
              <el-button type="text" size="small" @click="openFlowCharts">
                <svg-icon style="font-size:10px;" iconClass="flowIcon"/>
                流程 
              </el-button>
            </el-col>
          </el-row>
        </template>
      </avue-form> 
    <!-- 
      流程图对话框
     -->
    <el-dialog title="流程信息" width="85%" top="0vh"  :fullscreen='true' @opened="flowChartDialogOpened" :close-on-click-modal='false' :visible.sync="flowCharts">
      <div>
        <el-tabs type="border-card" class='tabClass' v-model="activeName"  @tab-click="handleTabChange">
          <el-tab-pane name="flowChart">
            <span slot="label"><svg-icon style="font-size:10px;" iconClass="flowIcon"/>流程图</span>
            <flow-charts ref="flowChart"></flow-charts>
          </el-tab-pane>
          <el-tab-pane name="flowTimeline">
            <span slot="label"><i class="el-icon-time"></i>流程处理记录</span>
            <flow-process-timeline ref="flowTimeline"></flow-process-timeline>
          </el-tab-pane>
        </el-tabs>
      </div>
     
    </el-dialog>
  </basic-container>
</template>

<script>
import {exportDynamicFormExcel,saveOrUpdateDynamicForm,saveOrUpdateDynamicFormList,saveDynamicForm,deleteDynamicForm,queryDynamicForm,queryDynamicFormListPage,updateDynamicForm,deleteDynamicFormList} from '@/api/system/dynamicFormApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import FlowCommonArea from '@/views/general/flow/generalFlowCommonArea.vue'
import FlowCharts from '@/views/general/flow/generalFlowProcessCharts.vue';
import FlowProcessTimeline from '@/views/general/flow/generalFlowProcessTimeline.vue';

export default {
  components: {
    FlowCommonArea,
    FlowCharts,
    FlowProcessTimeline
  },
  props: {
    processData: {
      type: Object
    },
    viewOnly: {
      type: Boolean
    },
  },
  data() {
    return {
      // 流程图对话框
      flowCharts: false,
      activeName: 'flowChart',

      //如果做流程表单 请将次开关设置为true，否则设置为false
      isFlow: true,
      flowArea: {},
      flowExtInfo: {},
      processFlowDialog:false,
      currentRow: {}, 
      processStatus: '',

      form: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        emptyBtn:false,
        submitBtn: false,
        tabs: false,
        column: [],
        group:[
          {
            arrow: false,
            column: [
              //以下区域为流程专用
              
              { 
                prop: 'flowExtInfo', 
                formslot: true,
                multiple: false,
                span: 258,
                dicData:[]
              }
            ]
          },
        ]
      },
      oldOption: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        emptyBtn:false,
        submitBtn: false,
        tabs: false,
        column: [],
        group:[
          {
            arrow: false,
            column: [
              //以下区域为流程专用
              { 
                prop: 'flowExtInfo', 
                formslot: true,
                multiple: false,
                span: 258,
                dicData:[]
              }
            ]
          },
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {},

      //动态表单参数
      currentForm: {},
      formCode: '',
      bizCode: ''
    };
  },

  computed: {
    ...mapGetters(['website','userInfo','orgTree','permission']),
    permissionList() {
      return {

      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: { 
    /**
     * 切换流程图标签时
     */
    handleTabChange(tab, event) {
      if(tab.name == 'flowTimeline'){
        this.$refs.flowTimeline.loadTimelineData(this.processData.id);
      }
    },
    /**
     * 打开流程图对话框
     */
    openFlowCharts(){
      this.flowCharts = true;
    },
    /**
     * 流程对话框打开之后 获取数据
     */
    flowChartDialogOpened(){
      this.$refs.flowChart.getFlowChartData(this.processData.id, this.processData.bizId);
    },
    /**
     * 根据ID获取记录，由主组件触发
     */
    async getRecordById(){
      this.processStatus = this.processData.processStatus ;
      this.reqParams.flowArea = {
        isFlow: true,
        processRecordId: this.processData.id
      }
      this.reqParams.singleBody =  {
        id: this.processData.bizId,
        bizCode: this.processData.bizCode
      }
      let commonData = reqCommonMsg(this.reqParams)
      await queryDynamicForm(commonData).then(res => {
        this.form = res.data.body.singleBody;
        this.currentRow = res.data.body.singleBody;
        this.flowArea = res.data.body.flowArea
        this.flowExtInfo = res.data.body.flowArea.flowExtData;
        //关闭myTask里的加载图标
        this.$emit('closeLoading','');
        let formJson = res.data.body.flowArea.formExtData;
        if(formJson != null){
          if(formJson.group){
            this.option.group = formJson.group.concat(this.option.group);
            //this.option.group.push.apply(this.option.group,formJson.group);
          }
          if(formJson.tabs){
            this.option.tabs = formJson.tabs;
          }
          if(this.option.column){
            this.option.column = formJson.column.concat(this.oldOption.column);
          }
        }
        //this.$console.log('==this.option.column333===',JSON.stringify(this.option));
        this.processFlowDialog = true;
        //表单group控制
        if(this.flowExtInfo){
          this.displayGroup(this.flowExtInfo.hideFormGroupList);
        }
        //表单栏位控制
        if(this.flowExtInfo){
          this.handelFormPrivilege(this.flowExtInfo.formPrivilege);
        }
      }, error => {
        //this.$console.log(error);
      });
    },
    /**
     * group显示控制
     */  
    displayGroup(formGroupList){
      //this.$console.log('formGroupList === ',formGroupList);
      // 按照group标签控制 
      if(this.option.group){
        formGroupList.forEach(element => {
          this.option.group.forEach((groupElement,index) => {
            if(groupElement.prop == element){
              groupElement.display = false;
            }
          });
        });
      }
    },
    /**
     * 处理表单权限
     */
    handelFormPrivilege(formPrivilege){
      formPrivilege.forEach(element => {
        // 不可见
        if(element.privilegeFlag == '0'){ 
          element.privilegeFormList.forEach(formElement => {
            this.hideForm(this.$toolUtil.toHump(formElement));
          });
        }
        //只读
        if(element.privilegeFlag == '1'){ 
          element.privilegeFormList.forEach(formElement => {
            this.readOnly(this.$toolUtil.toHump(formElement));
          });
        }
        // 必输
        if(element.privilegeFlag == '2'){ 
          element.privilegeFormList.forEach(formElement => {
            this.inputRequired(this.$toolUtil.toHump(formElement));
          });
        }
      });
      this.processFlowDialog = true;
    },
    //隐藏栏位
    hideForm(field){
      //无group的情况
      if(this.option.column){
        for(var i = 0; i < this.option.column.length; i++){
          if(this.option.column[i].prop == field){
            this.option.column[i].display = false;
            this.option.column[i].disabled = true;
            i = 10000;
          }
        }
      }
      if(this.option.group){
        this.option.group.forEach((element,index) => {
          if(element.column){
            for(var i = 0; i < element.column.length; i++){
              if(element.column[i].prop == field){
                element.column[i].display = false;
                element.column[i].disabled = true;
                i = 10000;
              }
            }
          }
        });
      }
    },
    //控制是否必输
    inputRequired(field){
      //无group的情况
      if(this.option.column){
        for(var i = 0; i < this.option.column.length; i++){
          if(this.option.column[i].prop == field){
            this.option.column[i].rules[0].required = true;
            i = 10000;
          }
        }
      }
      //有group 的情况
      if(this.option.group){
        this.option.group.forEach((element,index) => {
          if(element.column){
            for(var i = 0; i < element.column.length; i++){
              if(element.column[i].prop == field){
                //this.$console.log('====field====',field);
                element.column[i].rules[0].required = true;
                i = 10000;
              }
            }
          }
        });
      }
    },
    //只读控制
    readOnly(field){
      //无group的情况
      if(this.option.column){
        for(var i = 0; i < this.option.column.length; i++){
          if(this.option.column[i].prop == field){
            this.option.column[i].display = true;
            this.option.column[i].disabled = true;
            i = 10000;
          }
        }
      }
      //有group 的情况
      if(this.option.group){
        this.option.group.forEach((element,index) => {
          if(element.column){
            for(var i = 0; i < element.column.length; i++){
              if(element.column[i].prop == field){
                element.column[i].display = true;
                element.column[i].disabled = true;
                i = 10000;
              }
            }
          }
        });
      }
    },
    /**
     * 由于表单验证需要submit触发，此处触发提交事件
     */
    doProcessSubmit(){
      let tmpRow=JSON.stringify(this.form).replace(/\$/g,'_')
      this.currentRow = JSON.parse(tmpRow);
      this.flowArea.flowExtData = this.flowExtInfo; 
      //flowOptFlag 1-开始启动 2-处理流程 ,3-撤回 4-驳回
      this.flowArea.isFlow = true;
      this.flowArea.flowOptFlag = '2';
      this.$refs.flowProcessForm.submit();
    },

    /**
     * 提交撤回
     */
    onProcessCallBackSubmit(){
      this.$confirm('确定要撤回?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let tmpRow=JSON.stringify(this.form).replace(/\$/g,'_')
          this.currentRow = JSON.parse(tmpRow);
          this.flowArea.flowExtData = this.flowExtInfo; 
          //flowOptFlag 1-开始启动 2-处理流程 ,3-撤回 4-驳回
          this.flowArea.isFlow = true;
          this.flowArea.flowOptFlag = '3';
          this.$refs.flowProcessForm.submit();
        }).catch(() => {});
    },

    /**
     * 由于表单验证需要submit触发，此处触发提交事件
     */
    doProcessReject(){
      this.$confirm('确定要驳回?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let tmpRow=JSON.stringify(this.form).replace(/\$/g,'_')
          this.currentRow = JSON.parse(tmpRow);
          this.flowArea.flowExtData = this.flowExtInfo; 
          //flowOptFlag 1-开始启动 2-处理流程 ,3-撤回 4-驳回
          this.flowArea.isFlow = true;
          this.flowArea.flowOptFlag = '4';
          this.$refs.flowProcessForm.submit();
        }).catch(() => {});
    },
    /**
     * 提交审批 
     */
    onProcessSubmit(form,done){
      this.processFlow();
    },
    
    /**
     * flow-common-area 组件回调同步修改扩展信息
     */
    handleFlowExtInfoChange(val){
      this.flowExtInfo = val;
    },
    
    /**
     * 启动流程，执行流程方法
     */
    processFlow(){
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
      });
      this.reqParams.flowArea = this.flowArea
      this.reqParams.singleBody = this.currentRow;
      this.reqParams.extBody = {
        id: this.processData.bizId,
        bizCode:  this.processData.bizCode
      }
      this.commonData = reqCommonMsg(this.reqParams)
      updateDynamicForm(this.commonData).then(() => {
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
        //执行成功 关闭对话框
        this.$emit('closeProcessFlowDialog','');
        loading.close();
      }, error => {
        //this.$console.log(error); 
        loading.close();
      });
    },

  },
  created() {
  },
  mounted() {
  }
};
</script>
<style>
.tabClass{
  min-height: 700px;
}
</style>
